package com.imageim.yimirror.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.danikula.videocache.HttpProxyCacheServer;
import com.imageim.yimirror.R;
import com.imageim.yimirror.banner.VideoBanner;
import com.imageim.yimirror.base.BaseActivity;
import com.imageim.yimirror.base.BaseApplication;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.AdInfoBean;
import com.imageim.yimirror.bean.ShopConfigInfoBean;
import com.imageim.yimirror.bean.TokenBean;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.ui.SceneManager;
import com.imageim.yimirror.common.util.AnimUtil;
import com.imageim.yimirror.common.util.AppUtil;
import com.imageim.yimirror.common.util.CacheUtils;
import com.imageim.yimirror.common.util.ToastUtil;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.net.NetPresenterImpl;
import com.imageim.yimirror.net.NetView;
import com.imageim.yimirror.service.comm.CommonNetUtil;
import com.imageim.yimirror.service.statistic.StatisticSDK;
import com.taobao.sophix.SophixManager;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 首页  显示Banner图
 */
public class BannerActivity extends BaseActivity implements NetView, EasyPermissions.PermissionCallbacks {
    private static final String TAG = "BannerActivity";
    private static final String[] NEED_PERMISSIONS = {
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private static final int REQUEST_CODE = 123;

    private static final String[] URL_TITLE = {
            "ToB测试http://10.1.30.6:9008/",
            "ToB线上http://apitob.xxlimageim.com/",
            "ToB陈锦发http://10.1.30.243:9008/",
            "ToB张鹏程http://10.1.21.249:9008/",
            "ToB伍巍巍http://10.1.30.247:9008/",
            "ToB预发布http://api.prev.xxlimageim.com/"
    };
    private static final String[] URL = {
            "http://10.1.30.6:9008/",
            "http://apitob.xxlimageim.com/",
            "http://10.1.30.243:9009/",
            "http://10.1.21.249:9008/",
            "http://10.1.30.247:9009/",
            "http://api.prev.xxlimageim.com/"
    };
    @BindView(R.id.banner)
    VideoBanner mBanner;
    @BindView(R.id.iv_switchUrl)
    ImageView mIvSwitchUrl;
    @BindView(R.id.tv_test)
    TextView mTvTest;
    @BindView(R.id.iv_start)
    ImageView mIvStart;
    @BindView(R.id.iv_new_year_gold)
    ImageView mIvNewYearGold;
    @BindView(R.id.iv_new_year_quan1)
    ImageView mIvNewYearQuan1;
    @BindView(R.id.iv_new_year_quan2)
    ImageView mIvNewYearQuan2;
    @BindView(R.id.rl_red_packet)
    RelativeLayout mRlNewYear;

    private ArrayList<String> list = new ArrayList<>();
    private NetPresenterImpl mNetPresenter;
    private AnimationDrawable frameAnim;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        //        toast("mac:" + AppUtil.getMacAddress());

        UserUtil.setRedPacketSupport(-1);
    }


    @Override
    protected void initBundle() {
        logD("mac地址===" + AppUtil.getMacAddress());
        logD("BaseUrl=" + NetConstants.getBaseUrl());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_banner;
    }


    @Override
    protected void initView() {
        ButterKnife.bind(this);

        //切换环境
        switchBaseUrl();
    }

    @Override
    protected void initListener() {
    }

    @Override
    protected void initData() {
        //获取设备所需要的权限
        requestMyPermission();
        //获取Token
        getToken();

    }

    private void startAnim() {
        if (frameAnim != null && !frameAnim.isRunning()) {
            frameAnim.start();
        }
    }

    private void stopAnim() {
        if (frameAnim != null && frameAnim.isRunning()) {
            frameAnim.stop();
        }
    }


    /**
     * 获取Token
     */
    private void getToken() {
        mNetPresenter = new NetPresenterImpl(this);
        mNetPresenter.getObject(mContext, NetConstants.URL.TOKEN, null, TokenBean.class, MSG_TOKEN);
    }

    /**
     * 获取广告轮播图 视频
     */
    private void getAdInfo() {
        mNetPresenter.getObject(mContext, NetConstants.URL.GET_AD_INFO, null, AdInfoBean.class, MSG_AD_INFO);
    }

    /**
     * 获取店铺配置信息  是否显示购买区域。。。
     * 1.允许 2.不允许
     */
    private void getShopConfigInfo() {
        mNetPresenter.getObject(mContext, NetConstants.URL.GET_SHOP_CONFIG, null, ShopConfigInfoBean.class, MSG_SHOP_CONFIG);
    }


    private static final int MSG_TOKEN = 0x0001;
    private static final int MSG_AD_INFO = 0x0002;
    private static final int MSG_SHOP_CONFIG = 0x0003;

    @Override
    public void onLoadPre(int msgCode) {
        if (msgCode == MSG_TOKEN) {
            showLoading();
        }
    }

    @Override
    public void onLoadSuccess(Object result, int msgCode) {
        if (msgCode == MSG_TOKEN) {
            hideLoading();
            saveToken(result);
        } else if (msgCode == MSG_AD_INFO) {
            setAdInfo(result);
        } else if (msgCode == MSG_SHOP_CONFIG) {
            saveShopConfig(result);
        }
    }

    @Override
    public void onLoadFail(int errorCode, String errorMsg, int msgCode) {
        hideLoading();
        if (msgCode == MSG_TOKEN && errorCode == 999) {
            toast("该设备未入库~");
        } else {
            toast(errorMsg + errorCode);
        }
    }


    /**
     * 保存Token信息  并且获取店铺配置和广告轮播图
     */
    private void saveToken(Object result) {
        TokenBean tokenBean = (TokenBean) result;
        //获取token ,保存到SP文件中
        String token = tokenBean.getToken();
        if (!TextUtils.isEmpty(token)) {
            UserUtil.setToken(token);
            getShopConfigInfo();
            //            getAdInfo();
        }
    }

    /**
     * 设置轮播图和轮播视频
     */
    private void setAdInfo(Object result) {
        //根据红包活动是否支持设置轮播图和按钮
        int redPacketSupport = UserUtil.getRedPacketSupport();
        if (redPacketSupport == Constants.SUPPORT_RED_PACKET) {
            //支持红包活动
            mIvStart.setVisibility(View.GONE);
            mRlNewYear.setVisibility(View.VISIBLE);
            AnimUtil.rotateAnim(mIvNewYearGold, 3000, true);
            AnimUtil.rotateAnim(mIvNewYearQuan1, 3000, false);
            AnimUtil.rotateAnim(mIvNewYearQuan2, 3000, false);
        } else {
            mRlNewYear.setVisibility(View.GONE);
            mIvStart.setVisibility(View.VISIBLE);
            //帧动画
            mIvStart.setImageResource(R.drawable.banner_animlist);
            frameAnim = (AnimationDrawable) mIvStart.getDrawable();
            startAnim();
        }

        AdInfoBean adInfoBean = (AdInfoBean) result;
        if (adInfoBean != null) {
            List<AdInfoBean.AdPicListBean> adPicList = adInfoBean.getAdPicList();
            List<AdInfoBean.AdVideoListBean> adVideoList = adInfoBean.getAdVideoList();

            if (adPicList == null && adVideoList == null) {
                toast("轮播图未配置~");
                return;
            }

            list.clear();
            if (adPicList != null && adPicList.size() > 0) {
                for (int i = 0; i < adPicList.size(); i++) {
                    String photoUrl = adPicList.get(i).getPhotoUrl();
                    list.add(photoUrl);
                }
            }

            if (adVideoList != null && adVideoList.size() > 0) {
                HttpProxyCacheServer proxy = BaseApplication.getProxy(getApplicationContext());
                for (int i = 0; i < adVideoList.size(); i++) {
                    String proxyUrl = proxy.getProxyUrl(adVideoList.get(i).getPhotoUrl());
                    list.add(proxyUrl);
                }
            }

            if (list.size() > 0) {
                mBanner.setDataList(list);
                mBanner.setImgDelyed(5000);
                mBanner.startBanner();
                mBanner.startAutoPlay();
            } else {
                toast("轮播图未配置成功~");
            }
        }
    }

    /**
     * 保存店铺的配置信息
     */
    private void saveShopConfig(Object result) {
        ShopConfigInfoBean shopConfigInfoBean = (ShopConfigInfoBean) result;
        if (shopConfigInfoBean != null) {
            int redPacketSupport = shopConfigInfoBean.getRedPacketSupport();

            //TODO  测试用
            //            UserUtil.setRedPacketSupport(redPacketSupport);

            if (redPacketSupport != UserUtil.getRedPacketSupport()) {
                UserUtil.setRedPacketSupport(redPacketSupport);
                //获取轮播图
                getAdInfo();
            }
            //            getAdInfo();
            UserUtil.setShopBuyConfigInfo(shopConfigInfoBean.getBuyConfig());
            UserUtil.setShopMaleSupport(shopConfigInfoBean.getMaleSupport());
            //            UserUtil.setZqSupport(shopConfigInfoBean.getZqSupport());
            UserUtil.setRedPacketNumFlag(shopConfigInfoBean.getRedPacketNumFlag());
        }
    }


    private void switchBaseUrl() {
        if (AppUtil.isRelease()) {
            mIvSwitchUrl.setVisibility(View.GONE);
            mTvTest.setVisibility(View.GONE);
        } else {
            String baseUrl = CacheUtils.getString(mContext, "baseUrl");
            if (!TextUtils.isEmpty(baseUrl)) {
                NetConstants.setBaseUrl(baseUrl);
            }

            mTvTest.setText("当前环境B端：" + NetConstants.BASE_URL);
            mIvSwitchUrl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final AlertDialog dialog = new AlertDialog.Builder(mContext)
                            .setTitle("选择BaseUrl")
                            .setIcon(R.drawable.banner_icon_setting)
                            .setSingleChoiceItems(URL_TITLE, -1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    switch (which) {
                                        case 0:
                                            NetConstants.setBaseUrl(URL[0]);
                                            mTvTest.setText(MessageFormat.format("当前环境B端：{0}", URL_TITLE[0]));
                                            break;
                                        case 1:
                                            NetConstants.setBaseUrl(URL[1]);
                                            mTvTest.setText(MessageFormat.format("当前环境B端：{0}", URL_TITLE[1]));
                                            break;
                                        case 2:
                                            NetConstants.setBaseUrl(URL[2]);
                                            mTvTest.setText(MessageFormat.format("当前环境B端：{0}", URL_TITLE[2]));
                                            break;
                                        case 3:
                                            NetConstants.setBaseUrl(URL[3]);
                                            mTvTest.setText(MessageFormat.format("当前环境B端：{0}", URL_TITLE[3]));
                                            break;
                                        case 4:
                                            NetConstants.setBaseUrl(URL[4]);
                                            mTvTest.setText(MessageFormat.format("当前环境B端：{0}", URL_TITLE[4]));
                                            break;
                                        case 5:
                                            NetConstants.setBaseUrl(URL[5]);
                                            mTvTest.setText(MessageFormat.format("当前环境B端：{0}", URL_TITLE[5]));
                                            break;
                                        default:
                                    }
                                    dialog.dismiss();
                                    CacheUtils.setString(mContext, "baseUrl", NetConstants.BASE_URL);
                                    getToken();
                                }
                            }).create();
                    dialog.show();
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //System.gc()，Android5.0以上无效
        Runtime.getRuntime().gc();
        CommonNetUtil.uploadAppInfo();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        startAnim();
        SophixManager.getInstance().queryAndLoadNewPatch();
        //重新获取店铺配置信息  判断是否红包活动金额达到上限
        getShopConfigInfo();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopAnim();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBanner != null) {
            mBanner.destroy();
        }

        if (mNetPresenter != null) {
            mNetPresenter.onDestroy();
        }
    }


    @OnClick({R.id.iv_start, R.id.rl_red_packet})
    public void onViewClicked(View v) {
        if (v.getId() == R.id.iv_start) {
            goToScanFaceActivity();
        } else if (v.getId() == R.id.rl_red_packet) {
            goToScanFaceActivity();
        }
    }

    private void goToScanFaceActivity() {
        if (!TextUtils.isEmpty(UserUtil.getToken())) {
            StatisticSDK.onEvent(101);
            SceneManager.toScene(mContext, ScanFaceActivity.class, null);
        } else {
            ToastUtil.show("Token为空，请重启APP获取");
        }
    }


    //-------------------------------------动态权限申请--------------------------------------------------

    @AfterPermissionGranted(REQUEST_CODE)
    public void requestMyPermission() {
        if (hasPermissions()) {
            // Have permissions, do the thing!
        } else {
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.camera_record),
                    REQUEST_CODE,
                    NEED_PERMISSIONS);
        }
    }

    private boolean hasPermissions() {
        return EasyPermissions.hasPermissions(mContext, NEED_PERMISSIONS);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        logD("onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        logD("onPermissionsDenied:" + requestCode + ":" + perms.size());
        //        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
        if (perms.size() > 0) {
            new AppSettingsDialog.Builder(this).setTitle("温馨提示").setRationale("需要申请权限，请点击确认").build().show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            toast(hasPermissions() ? "权限申请成功" : "权限申请失败");
        }
    }

    //-------------------------------------权限申请--------------------------------------------------


}